package com.cheng.example.atguigu.view2.client44;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产者消费者之阻塞队列版
 * 这个是生产者消费者最简单的方式
 */
public class MyResource {
    private volatile boolean FlAG = true;
    BlockingQueue blockingQueue = null;

    AtomicInteger atomicInteger = new AtomicInteger();

    public MyResource(BlockingQueue blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    public void pro() throws InterruptedException {
        while (FlAG) {
            int v1 = atomicInteger.incrementAndGet();
            if (blockingQueue.offer(v1, 2, TimeUnit.SECONDS)) {
                System.out.println("生产:" + v1 + "\t成功");
            } else {
                System.out.println("生产:" + v1 + "\t失败");
            }
            TimeUnit.SECONDS.sleep(1);
        }
    }


    public void sonsume() throws InterruptedException {
        while (FlAG) {
            Object v1 = null;
            v1 = blockingQueue.poll(2, TimeUnit.SECONDS);
            if (v1 == null) {
            } else {
                System.out.println("消费:" + v1 + "\t成功");
            }
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println("终于叫停了");
    }

    public void stop() {
        FlAG = false;
    }

    public static void main(String[] args) throws InterruptedException {
        MyResource resource = new MyResource(new ArrayBlockingQueue(10));
        new Thread(() -> {
            try {
                resource.pro();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "生产者").start();

        new Thread(() -> {
            try {
                resource.sonsume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "消费者").start();

        TimeUnit.SECONDS.sleep(5);
        resource.stop();
    }
}
